<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import type { JianCeRow, ReusePartsRow, ReuseRow } from '../create'
import { useEntPageData } from '../createHelper'
import zhiWuEdit from './zhi.wu.edit.vue'
import zhiWuFenZuEdit from './zhi.wu.fen.edit.vue'
import jianceEdit from './jiance.edit.vue'
import { ModelType } from '@/types/common'
import type { doLoading } from '@/types/page'
import useEntStore from '@/store/modules/ent'
import entApi from '@/api/modules/ent'

const entStore = useEntStore()
const { refreshDevices } = entStore
const { isReadOnly } = useEntPageData()

const editRef = ref()

// 治污
function toCreate() {
  editRef.value.open({ type: ModelType.add })
}

function toEdit(row: ReuseRow) {
  editRef.value.open({ type: ModelType.edit, data: row })
}

async function submitEdit(formData: ReuseRow, doLoading: doLoading) {
  try {
    doLoading(true)
    const baseInfoObjID = entStore.currentEntData.baseInfo?.ObjID
    if (!baseInfoObjID) {
      return
    }
    const isCreate = !formData.ObjID
    const res = isCreate
      ? await entApi.ReuseAdd({
        enterpriseObjID: baseInfoObjID,
        reuse: { Name: formData.Name, Location: formData.Location, ObjID: '' },
      })
      : await entApi.ReuseUpdate({
        reuse: formData,
        reuseObjID: formData.ObjID,
      })

    await entApi.SetBindProduces({
      reuseObjID: isCreate ? res.ObjID : formData.ObjID,
      produceObjIDs: formData.ProduceIDs,
    })

    refreshDevices(baseInfoObjID)
    editRef.value.close()
    ElMessage.success({
      message: isCreate ? '新增成功' : '编辑成功',
      type: 'success',
    })
  }
  catch (e) {
    doLoading(false)
  }
}

async function delEnt(row: ReuseRow) {
  await ElMessageBox.confirm(`确定删除治理设施 "${row.Name}" 吗？`, '提示', {
    type: 'warning',
  })
  await entApi.ReuseDelete({ reuseObjID: row.ObjID })
  ElMessage.success({
    message: '删除成功',
    type: 'success',
  })
  refreshDevices(entStore.currentEntData.baseInfo?.ObjID)
}

// 分组
const fenzuRef = ref()
function toEditFenZu(row: ReusePartsRow) {
  fenzuRef.value.open({ type: ModelType.edit, data: row })
}

function toAddFenZu(row: ReuseRow) {
  fenzuRef.value.open({ type: ModelType.add, data: { ParentId: row.ObjID } })
}

async function submitFenZu(formData: ReusePartsRow, doLoading: doLoading) {
  try {
    doLoading(true)
    const isCreate = !formData.ObjID
    isCreate
      ? await entApi.AddReusePart({
        reuseObjID: formData.ParentId,
        reusePart: formData,
      })
      : await entApi.UpdateReusePart({
        reusePartObjID: formData.ObjID,
        reusePart: formData,
      })
    refreshDevices(entStore.currentEntData?.baseInfo?.ObjID)
    fenzuRef.value.close()
    ElMessage.success({
      message: isCreate ? '新增成功' : '编辑成功',
      type: 'success',
    })
  }
  catch (e) {
    doLoading(false)
  }
}

async function delFenZu(row: ReusePartsRow) {
  await ElMessageBox.confirm(`确定删除分组"${row.Name}" 吗？`, '提示', {
    type: 'warning',
  })
  await entApi.DeleteReusePart({ reusePartObjID: row.ObjID })
  ElMessage.success({
    message: '删除成功',
    type: 'success',
  })
  refreshDevices(entStore.currentEntData.baseInfo?.ObjID)
}

// 监测点
const jianceEditRef = ref()
function toEditJianCe(row: JianCeRow) {
  jianceEditRef.value.open({ type: ModelType.edit, data: row })
}

function toAddJianCe(row: ReusePartsRow) {
  jianceEditRef.value.open({ type: ModelType.add, data: { ParentId: row.ObjID } })
}

async function submitJianCe(formData: JianCeRow, doLoading: doLoading) {
  try {
    doLoading(true)
    const isCreate = !formData.ObjID
    isCreate
      ? await entApi.ReuseAddElectricDevice({
        reusePartObjID: formData.ParentId,
        electricDevice: formData,
      })
      : await entApi.ReuseUpdateElectricDevice({
        electricDevice: formData,
        electricDeviceObjID: formData.ObjID,
      })
    refreshDevices(entStore.currentEntData?.baseInfo?.ObjID)
    jianceEditRef.value.close()
    ElMessage.success({
      message: isCreate ? '新增成功' : '编辑成功',
      type: 'success',
    })
  }
  catch (e) {
    doLoading(false)
  }
}

async function delJianCe(row: JianCeRow, parent: ReusePartsRow) {
  await ElMessageBox.confirm(`确定删除监测点"${row.Name}" 吗？`, '提示', {
    type: 'warning',
  })
  await entApi.ReuseDeleteElectricDevice({ electricDeviceObjID: row.ObjID, reusePartObjID: parent.ObjID })
  ElMessage.success({
    message: '删除成功',
    type: 'success',
  })
  refreshDevices(entStore.currentEntData.baseInfo?.ObjID)
}

function showProduces(ids: string[]) {
  return ids.map((item: any) => {
    return entStore?.currentEntData?.Produces[item]?.Name || ''
  }).join('，')
}
</script>

<template>
  <div>
    <div v-if="!isReadOnly" class="mb-4 flex flex-justify-end">
      <el-button type="success" @click="toCreate">
        新增治理设施
      </el-button>
    </div>
    <div v-auto-height="50">
      <vxe-table
        auto-resize border height="100%" :loading="entStore.currentEntLoading" :data="entStore.Reuses"
        :row-config="{ isCurrent: true, keyField: 'ObjID' }" :expand-config="{
          accordion: true,
          reserve: true,
        }"
      >
        <vxe-column type="expand" width="80">
          <template #content="{ row }">
            <div class="p-4">
              <vxe-table border header-row-class-name="bg-#bae0ff" :data="row.Children" :row-config="{ isCurrent: true }">
                <vxe-column type="expand" width="80">
                  <template #content="{ row: ReuseChildRow }">
                    <div class="p-4">
                      <vxe-table
                        border header-row-class-name="bg-#bae0ff" :data="ReuseChildRow.Children"
                        :row-config="{ isCurrent: true }"
                      >
                        <vxe-column field="Name" title="治污监测点" min-width="100" />
                        <vxe-column field="AssetCode" title="资产号" min-width="100" />
                        <vxe-column field="MN" title="MN号" min-width="100" />
                        <vxe-column field="PointCode" title="采集因子" min-width="100" />
                        <vxe-column field="Location" title="安装位置" min-width="100" />
                        <VxeColumn field="PowerLimit" title="阈值（kW）" min-width="100" />
                        <vxe-column field="PowerDuration" title="时长（分钟）" min-width="100" :formatter="({ cellValue }) => Number(cellValue / 60).toFixed(2)" />
                        <VxeColumn v-if="!isReadOnly" field="operate" title="操作" width="200">
                          <template #default="{ row: DeviceRow }">
                            <ElButton link type="success" @click="toEditJianCe(DeviceRow)">
                              编辑
                            </ElButton>
                            <ElButton link type="danger" @click="delJianCe(DeviceRow, ReuseChildRow)">
                              删除
                            </ElButton>
                          </template>
                        </VxeColumn>
                      </vxe-table>
                    </div>
                  </template>
                </vxe-column>
                <vxe-column field="Name" title="分组名称" min-width="100" />
                <vxe-column field="Location" title="安装位置" min-width="100" />
                <vxe-column field="RunNum" title="至少同时运行数量" min-width="150" />
                <vxe-column field="ElectricDevices" title="监测点数量" width="150">
                  <template #default="{ row: RusePartRow }">
                    {{ RusePartRow.ElectricDevices.length }}
                  </template>
                </vxe-column>
                <VxeColumn v-if="!isReadOnly" field="operate" title="操作" width="200">
                  <template #default="{ row: ReuseEditRow }">
                    <ElButton link type="primary" @click="toAddJianCe(ReuseEditRow)">
                      新增监测点
                    </ElButton>
                    <ElButton link type="success" @click="toEditFenZu(ReuseEditRow)">
                      编辑
                    </ElButton>
                    <ElButton link type="danger" @click="delFenZu(ReuseEditRow)">
                      删除
                    </ElButton>
                  </template>
                </VxeColumn>
              </vxe-table>
            </div>
          </template>
        </vxe-column>
        <VxeColumn field="Name" title="治理设施名称" min-width="100" show-overflow />
        <VxeColumn field="Location" title="安装位置" min-width="100" />
        <VxeColumn field="Name" title="分组数量" width="80">
          <template #default="{ row }">
            {{ row.ReuseParts.length }}
          </template>
        </VxeColumn>
        <VxeColumn field="Name" title="关联产污设施" min-width="250">
          <template #default="{ row }">
            {{ showProduces(row.ProduceIDs || []) }}
          </template>
        </VxeColumn>
        <VxeColumn v-if="!isReadOnly" field="operate" title="操作" width="200">
          <template #default="{ row }">
            <ElButton link type="primary" @click="toAddFenZu(row)">
              新增分组
            </ElButton>
            <ElButton link type="success" @click="toEdit(row)">
              编辑
            </ElButton>
            <ElButton link type="danger" @click="delEnt(row)">
              删除
            </ElButton>
          </template>
        </VxeColumn>
      </vxe-table>
    </div>
    <zhiWuEdit ref="editRef" @submit="submitEdit" />
    <jianceEdit ref="jianceEditRef" @submit="submitJianCe" />
    <zhiWuFenZuEdit ref="fenzuRef" @submit="submitFenZu" />
  </div>
</template>
